const express = require("express")
// 创建router对象
const router = express.Router()
const path = require("node:path")
const fs = require("node:fs/promises")

const STUARR = require("../data/students.json")


// 学生列表的路由
router.get("/list",(req,res) => {
    res.render("students",{ stus:STUARR})
})

// 添加学生的路由
router.post("/addstu",(req,res) => {
    const id = STUARR.at(-1)?STUARR.at(-1).id + 1 : 1

    const newUser = {
        id,
        name:req.body.name,
        age:req.body.age,
        gender:req.body.gender,
        address:req.body.address
    }
    
    STUARR.push(newUser)

    fs.writeFile(
        path.resolve(__dirname,"../data/students.json"),
        JSON.stringify(STUARR)
    ).then(() => {
            
        res.redirect("/students/list")
    }).catch(() => {
            
    })
        
})

// 暴露router
module.exports = router